package com.vegetable.modules.controller.outbound;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.format.FastDateFormat;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.style.StyleUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.vegetable.common.annotation.PreventDuplicateSubmit;
import com.vegetable.common.annotation.SysLog;
import com.vegetable.common.utils.ExcelUtils;
import com.vegetable.common.utils.PageUtils;
import com.vegetable.common.utils.R;
import com.vegetable.modules.controller.AbstractController;
import com.vegetable.modules.entity.baseData.AddressBook;
import com.vegetable.modules.entity.baseData.ProductSpec;
import com.vegetable.modules.entity.baseData.Products;
import com.vegetable.modules.entity.outbound.SalesOrder;
import com.vegetable.modules.entity.outbound.SalesOrderDetail;
import com.vegetable.modules.entity.outbound.SalesOrderTransmit;
import com.vegetable.modules.entity.outbound.SalesOut;
import com.vegetable.modules.entity.outbound.excel.SalesOrderImport;
import com.vegetable.modules.entity.outbound.po.CustomerPurchaseAnalysisPO;
import com.vegetable.modules.entity.outbound.po.NoCostWeightListPO;
import com.vegetable.modules.entity.outbound.po.SalesAssignTaskPO;
import com.vegetable.modules.entity.outbound.po.SalesOrderTransmitPO;
import com.vegetable.modules.entity.outbound.vo.CustomerPurchaseAnalysisVO;
import com.vegetable.modules.service.baseData.IAddressBookService;
import com.vegetable.modules.service.baseData.IProductSpecService;
import com.vegetable.modules.service.baseData.IProductsService;
import com.vegetable.modules.service.outbound.ISalesOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static org.apache.poi.ss.usermodel.HorizontalAlignment.CENTER;

/**
 * <p>
 * 销售订货 前端控制器
 * </p>
 *
 * @author wangruijie
 * @since 2024-03-27
 */
@Slf4j
@RestController
@RequestMapping("/outStorage/salesOrder")
@AllArgsConstructor
@Api(value = "销售订货", tags = "销售订货")
public class SalesOrderController extends AbstractController {

    private ISalesOrderService salesOrderService;
    private IAddressBookService addressBookService;
    private IProductsService productsService;
    private IProductSpecService productSpecService;
    /**
     * 所有销售订货列表
     */
    @GetMapping("/list")
    @ApiOperation(value = "条件查询销售订货列表", notes = "条件查询销售订货列表")
    public R list(@RequestParam Map<String, Object> params){
        log.info("条件查询销售订货列表{}", JSON.toJSONString(params));
        PageUtils page = salesOrderService.queryPage(params);
        return R.data( page);
    }


    /**
     * 销售走货列表
     */
    @GetMapping("/salesOrderList")
    @ApiOperation(value = "销售走货列表", notes = "销售走货列表")
    public R salesOrderList(@RequestParam Map<String, Object> params){
        log.info("销售走货列表{}", JSON.toJSONString(params));
        PageUtils page = salesOrderService.salesOrderList(params);
        return R.data( page);
    }

    /**
     * 复制销售订货
     */
    @SysLog(value = "复制销售订货")
    @GetMapping("/copySalesOrder")
    @ApiOperation(value = "复制销售订货", notes = "复制销售订货")
    public R copySalesOrder(Long id) throws Exception {
        if (id == null || id == -1){
            return R.fail("订单主键不能为空");
        }
        log.info("复制销售订货：{}", JSON.toJSONString(id));
        return salesOrderService.copySalesOrder(id, getUserId());
    }

    /**
     * 详情销售订货
     */
    @SysLog(value = "详情销售订货")
    @GetMapping("/detailSalesOrder")
    @ApiOperation(value = "根据id查询详情销售订货", notes = "根据id查询详情销售订货")
    public R detailSalesOrder(Long id){
        if (id == null || id == -1){
            return R.fail("订单主键不能为空");
        }
        log.info("根据id查询详情销售订货：{}", JSON.toJSONString(id));
        return salesOrderService.detailSalesOrder(id);
    }

    /**
     * 新增销售订货
     */
    @SysLog(value = "新增销售订货")
    @PostMapping("/saveSalesOrder")
    @ApiOperation(value = "新增销售订货", notes = "新增销售订货")
    public R saveSalesOrder(@RequestBody SalesOrder salesOrder) throws Exception {
        log.info("新增销售订货：{}", JSON.toJSONString(salesOrder));
        salesOrder.setState(1);
        salesOrder.setCreateUserId(getUserId());
        return salesOrderService.saveSalesOrder(salesOrder);
    }

    @GetMapping("/exportTemplate")
    @ApiOperation(value = "导出销售订单模板", notes = "导出销售订单模板")
    public R exportTemplate(Long customerId) throws Exception {
        List<SalesOrderImport> orderList = new ArrayList<>();
        if(Objects.nonNull(customerId)){
            List<SalesOrderDetail> details = salesOrderService.relateOrder(customerId);
            if(CollectionUtil.isNotEmpty(details)){
                for(SalesOrderDetail detail : details){
                    SalesOrderImport im = new SalesOrderImport();
                    BeanUtils.copyProperties(detail, im);
//                    im.setStandard(detail.getStandard());
                    orderList.add(im);
                }
            }
        }else{
            throw new Exception("请选择客户");
        }
        AddressBook customer = addressBookService.queryById(customerId);
        ExportParams exportParams = new ExportParams();
        exportParams.setSheetName("销售出库详情");
        //开始导出
//        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, SalesOutExport.class, orderList);
        XSSFWorkbook workbook = new XSSFWorkbook();
        CellStyle cellStyle = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setBold(true);
        font.setFontName("黑体");
        font.setFontHeightInPoints((short) 16);
        cellStyle.setFont(font);
        cellStyle.setAlignment(CENTER);
        cellStyle.setBorderTop(BorderStyle.THIN);
        // 设置底部边框样式为粗实线，这里体现宽度变化，比细实线更粗
        cellStyle.setBorderBottom(BorderStyle.THIN);
        // 设置左边框样式为双实线，宽度也由对应的样式决定，双实线相对较粗
        cellStyle.setBorderLeft(BorderStyle.THIN);
        // 设置右边框样式为点划线，有其特定宽度表现
        cellStyle.setBorderRight(BorderStyle.THIN);


        XSSFSheet sheet = workbook.createSheet("Sheet1");
//        sheet.setColumnWidth(0, 20 * 256);
//        sheet.setColumnWidth(1, 30 * 256);
//        sheet.setColumnWidth(2, 20 * 256);
//        sheet.setColumnWidth(3, 20 * 256);
//        sheet.setColumnWidth(5, 20 * 256);
//        sheet.setColumnWidth(6, 25 * 256);
//        sheet.setColumnWidth(9, 20 * 256);
//        sheet.setColumnWidth(10, 20 * 256);
        XSSFRow titleRow = sheet.createRow(0 );
        XSSFCell customerNameCell = titleRow.createCell(0);
        customerNameCell.setCellValue("客户名称");
        CellRangeAddress customerNameRegion = new CellRangeAddress(
                0, // 起始行（0-based）
                0, // 结束行
                1, // 起始列（0-based）
                2  // 结束列
        );
        sheet.addMergedRegion(customerNameRegion);
        XSSFCell customerNameValueCell = titleRow.createCell(1);
        customerNameValueCell.setCellValue(customer.getAlias());
        CellRangeAddress orderTimeNameRegion = new CellRangeAddress(
                0, // 起始行（0-based）
                0, // 结束行
                3, // 起始列（0-based）
                5  // 结束列
        );
        sheet.addMergedRegion(orderTimeNameRegion);
        XSSFCell orderTimeNameCell = titleRow.createCell(3);
        orderTimeNameCell.setCellValue("发车日期");
        XSSFCell orderTimeValueCell = titleRow.createCell(6);
        orderTimeValueCell.setCellValue(FastDateFormat.getInstance("yyyy/MM/dd").format(new Date()));


        List<String> headRows = Arrays.asList("商品编码", "标重（市斤）", "品种", "规格", "件数", "走货数量", "备注", "毛重", "体积", "重量", "毛重合计", "体积合计");
        XSSFRow headRow = sheet.createRow(1 );
        for(int i = 0; i< headRows.size(); i++){
            XSSFCell cell = headRow.createCell(i);
            cell.setCellValue(headRows.get(i));
        }
        for (int index = 0; index < orderList.size(); index++) {
            int rowNum = index + 2;
            XSSFRow row = sheet.createRow(rowNum);
            SalesOrderImport detail = orderList.get(index);
//            // 客户名称
//            XSSFCell customerNameCell = row.createCell(0);
//            customerNameCell.setCellValue(detail.getCustomerName());
            // 商品编码
            XSSFCell commodityCodeCell = row.createCell(0);
            commodityCodeCell.setCellValue(detail.getCommodityCode());
            // 标重
            XSSFCell standardCell = row.createCell(1);
            standardCell.setCellValue(detail.getStandard().doubleValue() * 2);
            // 商品名称
            XSSFCell commodityNameCell = row.createCell(2);
            commodityNameCell.setCellValue(detail.getCommodityName());
            // 规格名称
            XSSFCell specsNameCell = row.createCell(3);
            specsNameCell.setCellValue(detail.getSpecsName());
            // 订单数量
            XSSFCell numberCell = row.createCell(4);
            numberCell.setCellValue(detail.getStartNumber().doubleValue());
            // 走货
            XSSFCell outNumberCell = row.createCell(5);
            outNumberCell.setCellValue("");
            // 备注
            XSSFCell remarkCell = row.createCell(6);
            remarkCell.setCellValue(detail.getRemark());
            // 单个毛重
            XSSFCell unitGrossWeightCell = row.createCell(7);
            unitGrossWeightCell.setCellValue(detail.getGrossWeight().doubleValue());
            // 单个体积
            XSSFCell unitVolumeCell = row.createCell(8);
            unitVolumeCell.setCellValue(detail.getVolume().doubleValue());
            // 订单重量
            XSSFCell weightCell = row.createCell(9);
            weightCell.setCellValue(detail.getStartWeight().doubleValue());
            if(NumberUtil.equals(BigDecimal.ZERO, detail.getStandard())){
                weightCell.setCellValue(0);
            }else{
                weightCell.setCellFormula("E" + (rowNum + 1) + "*B" + (rowNum + 1));
            }
            // 总毛重
            XSSFCell grossWeightCell = row.createCell(10);
            grossWeightCell.setCellFormula("E" + (rowNum + 1) + "*H" + (rowNum + 1));
            // 总体积
            XSSFCell grossVolumeCell = row.createCell(11);
            grossVolumeCell.setCellFormula("E" + (rowNum + 1) + "*I" + (rowNum + 1));
        }
        XSSFRow sumRow = sheet.createRow(orderList.size() + 2);
        XSSFCell oneCell = sumRow.createCell(0);
        oneCell.setCellValue("合计");
        XSSFCell totalNumberCell = sumRow.createCell(4);
        totalNumberCell.setCellFormula("SUM(E"+3+":E"+(orderList.size() + 2) +")");
        XSSFCell totalWeightCell = sumRow.createCell(9);
        totalWeightCell.setCellFormula("SUM(J"+3+":J"+(orderList.size() + 2) +")");
        XSSFCell totalGrossWeightCell = sumRow.createCell(10);
        totalGrossWeightCell.setCellFormula("SUM(K"+3+":K"+(orderList.size() + 2) +")");
        XSSFCell totalVolumeCell = sumRow.createCell(11);
        totalVolumeCell.setCellFormula("SUM(L"+3+":L"+(orderList.size() + 2) +")");
        XSSFRow remarkRow = sheet.createRow(orderList.size() + 3);
        XSSFCell remarkNameCell = remarkRow.createCell(0);
        remarkNameCell.setCellValue("备注");
        CellRangeAddress mergedRegion = new CellRangeAddress(
                orderList.size() + 3, // 起始行（0-based）
                orderList.size() + 3, // 结束行
                1, // 起始列（0-based）
                10  // 结束列
        );
        sheet.addMergedRegion(mergedRegion);
        XSSFCell remarkValueCell = remarkRow.createCell(1);
        remarkValueCell.setCellValue("");


        for (int i = 0; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            if (row!= null) {
                for (int j = 0; j < row.getLastCellNum(); j++) {
//                    Cell ccell = row.getCell(j);
                    Cell ccell = row.getCell(j) == null ? row.createCell(j) : row.getCell(j);
//                    if (ccell!= null) {
                        ccell.setCellStyle(cellStyle);
//                    }
                }
            }
        }
        StyleUtil.createHeadCellStyle(workbook);

        // 自动调整列宽
        for (int i = 0; i < headRows.size(); i++) {
            sheet.autoSizeColumn(i);
        }

        String fileName = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        ExcelUtils.downLoadExcel(fileName,workbook);
        return R.success("");
    }

    /**
     * 批量导入销售订单
     */
    @ApiOperation("Upload Excel")
    @PostMapping("/uploadSalesOrder")
    public R  batchSaveSalesOrder(@RequestParam(value = "file", required = true) MultipartFile file) throws Exception {
        Workbook workbook = WorkbookFactory.create(file.getInputStream());
        Sheet sheet = workbook.getSheetAt(0);
        // 标题行
        Row titleRow = sheet.getRow(0);
        String customerName = titleRow.getCell(1).getStringCellValue().replace("\\s+", "").trim();
        Date orderTime = new Date();
        // 日期格
        Cell dateCell = titleRow.getCell(6);
        CellType cellType = dateCell.getCellType();
        switch (cellType){
            case NUMERIC:
                orderTime = dateCell.getDateCellValue();
                break;
            case STRING:
                String orderTimeStr = dateCell.getStringCellValue();
                orderTime = StrUtil.isBlank(orderTimeStr) ? new Date() : DateUtil.parse(orderTimeStr, "yyyy/MM/dd");
                break;
            default:

                break;
        }
        ImportParams importParams = new ImportParams();
        importParams.setTitleRows(1);
        importParams.setHeadRows(1);
        List<SalesOrderImport> orderListTmp = ExcelImportUtil.importExcel(file.getInputStream(), SalesOrderImport.class, importParams);
        List<SalesOrderImport> orderListImport = new ArrayList<>();
        for(SalesOrderImport im : orderListTmp){
            if(StrUtil.isNotBlank(im.getCommodityCode())){
                orderListImport.add(im);
            }
        }
        // 备注行
        Row remarkRow = sheet.getRow(orderListImport.size() + 1);
        // 失败原因列表
//        List<String> failReasons = new ArrayList<>();
        // 验证导入数量
        if(CollectionUtil.isEmpty(orderListImport)){
            String failReason = "导入的表格不能为空";
            throw new RuntimeException(failReason);
        }
        List<SalesOrderImport> orderList = orderListImport.subList(0, orderListImport.size() - 2 );
        // 客户只能是一个
        Map<String, Object> map = new HashMap<>();
//        // 验证客户是否存在
//        String customerName = orderList.get(0).getCustomerName();
        AddressBook customer = addressBookService.queryByAliseName(customerName, 1);
        if(Objects.isNull(customer)){
            String failReason = "客户《" + customerName + "》不存在";
            throw new RuntimeException(failReason);
        }
        // 验证商品是否存在
        List<SalesOrderDetail> commodities = new ArrayList<>();
        for(SalesOrderImport order : orderList){
            if(Objects.isNull(order.getStartNumber()) || order.getStartNumber() <= 0){
                continue;
            }
            if(StrUtil.isBlank(order.getCommodityCode())){
                log.info("商品编码《" + order.getCommodityCode() + "》不存在");
                throw new RuntimeException("商品编码《" + order.getCommodityCode() + "》不存在");
            }
            map.put(order.getCustomerName(), order.getCustomerName());
            Products product = productsService.queryByCommonCode(order.getCommodityCode().replace("\\s+", "").trim());
            if(Objects.isNull(product)){
                String failReason = "商品编码《" + order.getCommodityCode() + "》不存在";
                throw new RuntimeException(failReason);
            }else{
                // 验证商品规格是否存在
//                ProductSpec spec = new ProductSpec();
                SalesOrderDetail detail = new SalesOrderDetail();
                List<ProductSpec> specList = productSpecService.queryByProductId(product.getId());
                if(CollectionUtil.isEmpty(specList)){
                    //
                    log.info("{}没有规格, 不需要设置", product.getId());
                }else{
                    Optional<ProductSpec> opt = specList.stream().filter(el -> el.getName().equals(order.getSpecsName())).findAny();
                    if(opt.isPresent()){
                        detail.setSpecsId(opt.get().getId());
                        detail.setSpecsName(opt.get().getName());
                    }else{
                        log.info("{}有规格，分别是{},但是excel中想找的规格是{}，没有发现。现在给他赋值第一个{}", product.getId(), JSONArray.toJSONString(specList), order.getSpecsName(), specList.get(0));
                        throw new RuntimeException(product.getCommonName()+"没有规格：" + order.getSpecsName());
//                        detail.setSpecsId(specList.get(0).getId());
//                        detail.setSpecsName(specList.get(0).getName());
                    }
                }
                BigDecimal orderWeight = NumberUtil.mul(order.getStartNumber(), product.getStandardWeight());
                detail.setCommodityId(product.getId());
                detail.setCommodityName(product.getCommonName());
                detail.setStandard(product.getStandardWeight());
                detail.setNumber(order.getStartNumber());
                detail.setWeight(orderWeight);
                detail.setStartNumber(order.getStartNumber());
                detail.setStartWeight(orderWeight);
                detail.setGrossWeight(order.getUnitGrossWeight());
                detail.setVolume(order.getUnitVolume());
                detail.setRemark(order.getRemark());
//                if(StringUtils.isNotBlank(order.getSpecsName())){
//                    spec = productSpecService.queryByProductId(product.getId().toString(), order.getSpecsName().replace("\\s+", "").trim());
//                }
//                if(Objects.isNull(spec)){
//                    String failReason = "商品规格《" + order.getSpecsName() + "》不存在";
//                    log.info(failReason);
//                    throw new RuntimeException(failReason);
//                }else{

                    commodities.add(detail);
//                }
            }
        }
        if (map.size() > 1){
            String failReason = "存在不同客商，请检查修改数据";
            throw new RuntimeException(failReason);
        }
        // 导入订单数据
        SalesOrder order = new SalesOrder();
        order.setCustomerId(customer.getId());
        order.setCustomerName(customer.getNoteName());
        order.setOrderTime(orderTime);
        order.setPurchaseTime(orderTime);
        order.setCreateUserId(getUserId());
        order.setIsTransmit(0);
        order.setCommodities(commodities);
        order.setRemark(ExcelUtils.getStringCell(remarkRow, 1));
        salesOrderService.saveSalesOrder(order);
        return R.status(true);
    }

    /**
     * 销售订单确认
     */
    @SysLog(value = "销售订单确认")
    @PostMapping("/confirmSalesOrder")
    @PreventDuplicateSubmit(expireTime = 5)
    @ApiOperation(value = "销售订单确认", notes = "销售订单确认")
    public R confirmSalesOrder(@RequestBody SalesOrder salesOrder) throws Exception {
        log.info("销售订单确认：{}", JSON.toJSONString(salesOrder));
        if (salesOrder.getId() == null || salesOrder.getId() == -1){
            return R.fail("订单主键不能为空");
        }
        salesOrder.setIsFirst(1);
        salesOrder.setIsTransmit(1);
        salesOrder.setCreateUserId(getUserId());

        return salesOrderService.confirmSalesOrder(salesOrder);
    }

    /**
     * 修改销售订货
     */
    @SysLog(value = "修改销售订货")
    @PostMapping("/updateSalesOrder")
    @ApiOperation(value = "修改销售订货", notes = "修改销售订货")
    public R updateSalesOrder(@RequestBody SalesOrder salesOrder) throws Exception {
        log.info("修改销售订货：{}", JSON.toJSONString(salesOrder));
        if (salesOrder.getId() == null || salesOrder.getId() == -1){
            return R.fail("订单主键不能为空");
        }
        salesOrder.setIsFirst(0);
        salesOrder.setCreateUserId(getUserId());
        return salesOrderService.updateSalesOrder(salesOrder);
    }


    /**
     * 任务下达列表
     */
    @PostMapping("/transmitList")
    @ApiOperation(value = "条件查询任务下达列表", notes = "条件查询任务下达列表")
    public R transmitList(@RequestBody SalesOrderTransmitPO po){
        log.info("条件查询任务下达列表{}", JSON.toJSONString(po));
        List<SalesOrderTransmit> page = salesOrderService.transmitList(po);
        return R.data( page);
    }

    /**
     * 任务下达
     */
    @SysLog(value = "任务下达")
    @PostMapping("/assignTask")
    @ApiOperation(value = "任务下达", notes = "修改销售订货")
    public R assignTask(@RequestBody SalesAssignTaskPO po) throws Exception {
        log.info("任务下达：{}", JSON.toJSONString(po));
        return salesOrderService.assignTask(po);
    }

    /**
     * 销售订货下的走货
     */
    @SysLog(value = "销售订货下的走货")
    @PostMapping("/submitSalesOrder")
    @PreventDuplicateSubmit(expireTime = 5)
    @ApiOperation(value = "销售订货下的走货", notes = "销售订货下的走货")
    public R submitSalesOrder(@RequestBody SalesOrder salesOrder) throws Exception {
        log.info("销售订货走货：{}", JSON.toJSONString(salesOrder));
        if (salesOrder.getId() == null || salesOrder.getId() == -1){
            return R.fail("订单主键不能为空");
        }
        return salesOrderService.submitSalesOrder(salesOrder);
    }

    @SysLog(value = "更新销售订单明细备注")
    @PreventDuplicateSubmit(expireTime = 5)
    @PostMapping("/submitRemark")
    @ApiOperation(value = "更新销售订单明细备注", notes = "更新销售订单明细备注")
    public R submitRemark(@RequestBody SalesOrder po) throws Exception {
        log.info("销售订货走货：{}", JSON.toJSONString(po));
        return salesOrderService.updateRemark(po);
    }

    /**
     * 销售走货
     */
    @SysLog(value = "销售走货")
    @PostMapping("/deliverySalesOrder")
    @ApiOperation(value = "销售走货", notes = "销售走货")
    public R deliverySalesOrder(@RequestBody SalesOrderDetail detail) throws Exception {
        log.info("常规销售走货：{}", JSON.toJSONString(detail));
        List<String> noRoleUsers = Arrays.asList("f008", "f010", "f011", "f018", "f022", "f028");
        String currentUser = getUser().getUsername();
        if(noRoleUsers.contains(currentUser)){
            throw new Exception("当前操作人" + currentUser + "无权操作走货.");
        }
        if (detail.getId() == null || detail.getId() == -1){
            return R.fail("商品明细主键不能为空");
        }
        return salesOrderService.deliverySalesOrder(detail);
    }

    /**
     * 销售订货_发货
     */
    @SysLog(value = "销售订货_发货")
    @GetMapping("/buildSendGoods")
    @ApiOperation(value = "根据id查询详组装发货数据（销售出库单）", notes = "根据id查询详组装发货数据（销售出库单）")
    public R<SalesOut> buildSendGoods(Long id)  {
        if (id == null || id == -1){
            return R.fail("订单主键不能为空");
        }
        log.info("根据id查询详情销售订货：{}", JSON.toJSONString(id));
        try {
            return salesOrderService.buildSendGoods(id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 完成销售订货
     */
    @SysLog(value = "完成销售订货")
    @GetMapping("/competeSalesOrder")
    @ApiOperation(value = "完成销售订货", notes = "完成销售订货")
    public R competeSalesOrder(Long id){
        log.info("完成销售订货：{}", JSON.toJSONString(id));
        try {
            return salesOrderService.competeSalesOrder(id);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("错误信息:{}",e.getLocalizedMessage());
            return R.fail(e.getMessage());
        }
    }
    /**
     * 删除销售订货
     */
    @SysLog(value = "删除销售订货")
    @GetMapping("/deleteSalesOrder")
    @ApiOperation(value = "根据id删除销售订货", notes = "根据id删除销售订货")
    public R deleteSalesOrder(Long id){
        log.info("删除销售订货：{}", JSON.toJSONString(id));
        try {
            return salesOrderService.deleteSalesOrder(id);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("错误信息:{}",e.getLocalizedMessage());
            return R.fail(e.getMessage());
        }
    }

    @SysLog(value = "一健走货")
    @GetMapping("/oneClickShipping")
    @ApiOperation(value = "一健走货", notes = "一健走货")
    public R oneClickShipping(Long orderId) throws Exception {
        String userId = getUser().getUsername();
        List<String> operatorIdList = Arrays.asList("f005", "f007");
        if(!operatorIdList.contains(userId)){
            throw new Exception("当前操作人无权操作一键走货.");
        }
        log.info("一健走货：{}", JSON.toJSONString(orderId));
        return salesOrderService.oneClickShipping(orderId);
    }
//    long curPage = 1;
//    long limit = 10;
    @GetMapping("/lastOrder")
    @ApiOperation(value = "查询客户最近的一次销售订单", notes = "查询客户最近的一次销售订单", response = SalesOrderDetail.class)
    public R lastOrder(Long customerId){
        List<SalesOrderDetail> details = salesOrderService.lastOrder(customerId);
        return R.data(details);
    }

    @SysLog(value = "查询没有走货的订单")
    @PostMapping("/noCostWeightList")
    @ApiOperation(value = "查询没有走货的订单", notes = "查询没有走货的订单")
    public R noCostWeightList(@RequestBody NoCostWeightListPO po) throws Exception {
        log.info("查询没有走货的订单：{}", JSON.toJSONString(po));
        return salesOrderService.noCostWeightList(po);
    }

    @GetMapping("/statisticTask")
    @ApiOperation(value = "统计小包装任务任务", notes = "导出销售订单模板")
    public R statisticTask(SalesOrderTransmitPO po) throws Exception {
        po.setCategory("小包装");
        List<Map<String, String>> dataList = salesOrderService.statisticTask(po);
        if (CollectionUtil.isEmpty(dataList)) {
            throw new Exception("暂时没有下发商品");
        }
        XSSFWorkbook workbook = new XSSFWorkbook();

        // 创建两种行样式
        CellStyle evenRowStyle = ExcelUtils.createRowStyle(workbook, IndexedColors.LIGHT_GREEN);
        CellStyle oddRowStyle = ExcelUtils.createRowStyle(workbook, IndexedColors.LIGHT_YELLOW);
        CellStyle headerStyle = ExcelUtils.createHeaderStyle(workbook);
        CellStyle titleStyle = ExcelUtils.createTitleStyle(workbook);
//        CellStyle cellStyle = workbook.createCellStyle();
//        Font font = workbook.createFont();
//        font.setBold(true);
//        font.setFontName("黑体");
//        font.setFontHeightInPoints((short) 16);
//        cellStyle.setFont(font);
//        cellStyle.setAlignment(CENTER);
//        cellStyle.setBorderTop(BorderStyle.THIN);
//        // 设置底部边框样式为粗实线，这里体现宽度变化，比细实线更粗
//        cellStyle.setBorderBottom(BorderStyle.THIN);
//        // 设置左边框样式为双实线，宽度也由对应的样式决定，双实线相对较粗
//        cellStyle.setBorderLeft(BorderStyle.THIN);
//        // 设置右边框样式为点划线，有其特定宽度表现
//        cellStyle.setBorderRight(BorderStyle.THIN);


        XSSFSheet sheet = workbook.createSheet("Sheet1");

        XSSFRow titleRow = sheet.createRow(0);
        Cell customerNameCell = titleRow.createCell(0);
        customerNameCell.setCellValue(DateUtil.today() + "小包装工作统计");
        CellRangeAddress customerNameRegion = new CellRangeAddress(
                0, // 起始行（0-based）
                0, // 结束行
                0, // 起始列（0-based）
                dataList.get(0).size()  // 结束列
        );
        sheet.addMergedRegion(customerNameRegion);
//        List<String> headRows = Arrays.asList("商品编码", "标重（市斤）", "品种", "规格", "件数", "走货数量", "备注", "毛重", "体积", "重量", "毛重合计", "体积合计");
//        XSSFRow headRow = sheet.createRow(1);
//        for (int i = 0; i < headRows.size(); i++) {
//            XSSFCell cell = headRow.createCell(i);
//            cell.setCellValue(headRows.get(i));
//        }
        customerNameCell.setCellStyle(titleStyle);  // 表头样式
        for (int index = 0; index < dataList.size(); index++) {
            int rowNum = index + 1;
            Row row = sheet.createRow(rowNum);
            Map<String, String> detailMap = dataList.get(index);
            List<String> keys = new ArrayList<>(detailMap.keySet());
//
//            for (int i = 0; i < keys.size(); i++) {
//                if (row != null) {
//                    for (int j = 0; j < keys.size(); j++) {
//                        String currentKey = keys.get(j);
//                        Cell ccell = row.getCell(j) == null ? row.createCell(j) : row.getCell(j);
//                        ccell.setCellStyle(cellStyle);
//                        ccell.setCellValue(detailMap.get(currentKey));
////                    }
//                    }
//                }
//            }
//            Row row = sheet.createRow(index);

            // 设置行样式
            if (index <= 2) {
                row.setRowStyle(headerStyle);  // 表头样式
            } else {
                // 间隔行设置不同样式
                CellStyle style = (index % 2 == 0) ? evenRowStyle : oddRowStyle;
                row.setRowStyle(style);
            }

//            // 填充单元格数据
//            for (int j = 0; j < rowData.length; j++) {
//                Cell cell = row.createCell(j);
//                cell.setCellValue(rowData[j]);
//
//                // 应用行样式到单元格
//                if (row.getRowStyle() != null) {
//                    cell.setCellStyle(row.getRowStyle());
//                }
//            }
            for (int i = 0; i < keys.size(); i++) {
                if (row != null) {
                    for (int j = 0; j < keys.size(); j++) {
                        String currentKey = keys.get(j);
                        Cell ccell = row.getCell(j) == null ? row.createCell(j) : row.getCell(j);
//                        ccell.setCellStyle(cellStyle);
                        ccell.setCellValue(detailMap.get(currentKey));

                        // 应用行样式到单元格
                        if (row.getRowStyle() != null) {
                            ccell.setCellStyle(row.getRowStyle());
                        }
//                    }
                    }
                }
            }
        }
        Cell teamCell = sheet.getRow(1).createCell( dataList.get(0).size() + 1);
        teamCell.setCellValue("加工人员(务必确认好自己加工的件数)");
        CellRangeAddress teamRegion = new CellRangeAddress(
                1, // 起始行（0-based）
                1, // 结束行
                dataList.get(0).size() + 1, // 起始列（0-based）
                dataList.get(0).size() + 15 // 结束列
        );
        sheet.addMergedRegion(teamRegion);
        Cell carCell = sheet.getRow(2).createCell( 0);
        carCell.setCellValue("车辆");
        CellRangeAddress carRegion = new CellRangeAddress(
                2, // 起始行（0-based）
                3, // 结束行
                0, // 起始列（0-based）
                0 // 结束列
        );
        sheet.addMergedRegion(carRegion);
        Cell categoryCell = sheet.getRow(4).createCell( 0);
        categoryCell.setCellValue("小包装");
        CellRangeAddress categoryRegion = new CellRangeAddress(
                4, // 起始行（0-based）
                dataList.size(), // 结束行
                0, // 起始列（0-based）
                0 // 结束列
        );
        sheet.addMergedRegion(categoryRegion);
//        List<String> headRows = Arrays.asList("商品编码", "标重（市斤）", "品种", "规格", "件数", "走货数量", "备注", "毛重", "体积", "重量", "毛重合计", "体积合计");
//        XSSFRow headRow = sheet.createRow(1);
//        for (int i = 0; i < headRows.size(); i++) {
//            XSSFCell cell = headRow.createCell(i);
//            cell.setCellValue(headRows.get(i));
//        }
//        customerNameCell.setCellStyle(titleStyle);  // 表头样式




//            StyleUtil.createHeadCellStyle(workbook);
        Map<String, String> detailMap = dataList.get(0);
        List<String> keys = new ArrayList<>(detailMap.keySet());
            // 自动调整列宽
            for (int i = 0; i < keys.size(); i++) {

                sheet.autoSizeColumn(i);
                log.info("{}的宽度---》{}", sheet.getColumnWidth(i), keys.get(i));
            }
            String fileName = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            ExcelUtils.downLoadExcel(fileName, workbook);
            return R.success("");
        }
        
    /**
     * 分析客户采购习惯
     */
    @PostMapping("/analyzeCustomerPurchase")
    @ApiOperation(value = "分析客户采购习惯", notes = "分析每个客户customer_id经常采购的商品，注意区分规格。注意要加上商品类型搜索")
    public R analyzeCustomerPurchase(@RequestBody CustomerPurchaseAnalysisPO po) {
        log.info("分析客户采购习惯：{}", JSON.toJSONString(po));
        IPage<CustomerPurchaseAnalysisVO> page = salesOrderService.analyzeCustomerPurchase(po);
        return R.data(page);
    }
}
